<template>
  <scroll-view
    class="scroll-list"
    scroll-y
    :refresher-enabled="true"
    :refresher-triggered="refreshing"
    :refresher-threshold="60"
    :lower-threshold="50"
    @refresherrefresh="onRefresh"
    @scrolltolower="onLoadMore"
  >
  
    <view class="content-box" :style="contentStyle" v-if="list.length">
        <!-- 列表内容 -->
        <slot v-for="(item, index) in list" :item="item" :index="index" :key="index"></slot>
    </view>
    <!-- 空数据 -->
    <view v-else class="empty-box">
      <slot name="empty">暂无数据</slot>
    </view>

    <!-- 加载状态 -->
    <view v-if="loadingMore" class="loading-box">加载中...</view>
    <view v-else-if="noMore && list.length" class="nomore-box">没有更多了</view>
  </scroll-view>
</template>

<script setup>
import { ref } from 'vue'

const props = defineProps({
  request: { type: Function, required: true }, // API函数 (接收 {page, pageSize} 返回Promise<{list, total}>)
  pageSize: { type: Number, default: 10 }, // 每页条数
  immediate: { type: Boolean, default: true } ,// 是否页面挂载后立即加载
  contentStyle: { type: String, default: '' }
})

const list = ref([])
const page = ref(1)
const total = ref(0)

const refreshing = ref(false)
const loadingMore = ref(false)
const noMore = ref(false)

// 下拉刷新
function onRefresh() {
  refreshing.value = true
  page.value = 1
  loadData(true)
}

// 上拉加载更多
function onLoadMore() {
  if (loadingMore.value || noMore.value) return
  page.value++
  loadData()
}

// 请求数据
async function loadData(isRefresh = false) {
  try {
    if (!isRefresh) loadingMore.value = true
    const res = await props.request({ page: page.value, pageSize: props.pageSize })

    const newList = res.list || []
    total.value = res.total || 0

    if (isRefresh) {
      list.value = newList
    } else {
      list.value = [...list.value, ...newList]
    }

    noMore.value = list.value.length >= total.value
  } catch (e) {
    console.error('加载失败:', e)
  } finally {
    refreshing.value = false
    loadingMore.value = false
  }
}

// 初始化
if (props.immediate) {
  loadData(true)
}

// 暴露方法给父组件
defineExpose({ reload: () => onRefresh() })
</script>

<style scoped>
.scroll-list {
  height: 100%;
  
 
}

.loading-box,
.nomore-box,
.empty-box {
  text-align: center;
  padding: 30rpx 0;
  color: #999;
  font-size: 28rpx;
}
</style>
